/**
 * 2010(c) Copyright Oceansoft Information System Co.,LTD. All rights reserved.
 * <p/>
 * Compile: JDK 1.6+
 * <p/>
 * 版权所有(C)：江苏欧索软件有限公司
 * <p/>
 * 公司名称：江苏欧索软件有限公司
 * <p/>
 * 公司地址：中国苏州科技城青山路1号
 * <p/>
 * 网址: http://www.oceansoft.com.cn
 * <p/>
 * 作者: 090922(陈伟)
 * <p/>
 * 文件名: com.oceansoft.mobile.biz.front.controller.ChannelController.java
 * <p/>
 * 类产生时间: 2014/3/27 21:12
 * <p/>
 * 负责人: 090922(陈伟)
 * <p/>
 * Email:javacspring@gmail.com
 * <p/>
 * 所在组 : 掌上公安应用平台
 * <p/>
 * 所在部门: 开发部--手持技术部
 * <p/>
 * <p/>
 */
package com.oceansoft.mobile.biz.admin.controller;

import static com.oceansoft.mobile.common.Constant.BIZ_FILE_PATH_PREFIX;
import static org.springframework.web.bind.annotation.RequestMethod.DELETE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.biz.admin.service.ICountAdminService;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.HtmlUtils;

import com.oceansoft.mobile.biz.admin.entity.BasesiteArticlePic;
import com.oceansoft.mobile.biz.admin.entity.Merchant;
import com.oceansoft.mobile.biz.admin.entity.NewsArticle;
import com.oceansoft.mobile.biz.admin.entity.SysUser;
import com.oceansoft.mobile.biz.admin.service.IBaseSiteAttachmentService;
import com.oceansoft.mobile.biz.admin.service.IMerchantService;
import com.oceansoft.mobile.biz.admin.service.INewsService;
import com.oceansoft.mobile.biz.api.entity.News;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.base.entity.FormItem;
import com.oceansoft.mobile.common.base.entity.Pager;
import com.oceansoft.mobile.common.base.entity.Query;
import com.oceansoft.mobile.common.base.entity.Result;
import com.oceansoft.mobile.weixin.entity.message.req.SuperMessage;
import com.oceansoft.mobile.weixin.service.WechatService;
import com.oceansoft.mobile.weixin.util.DateUtil;

/**
 * 新闻前端控制器
 *
 * @author Administrator
 *
 */
@Controller
@RequestMapping("admin/police")
public class PoliceAminController {
    @Resource
    private INewsService newsService;
    @Resource
    private IMerchantService merchantService;
    @Resource
    private IBaseSiteAttachmentService attachmentService;
    @Resource
    private WechatService wechatService;

    @Resource
    private ICountAdminService countAdminService;


    /**
     * 后台进入新闻发布
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "index", method = GET)
    public String gotoChannelList(Model model) {
        return "admin/police/news-list";
    }

    @ResponseBody
    @RequestMapping(value = "newslist", method = GET)
    public Pager<NewsArticle> gotoNewsList(HttpSession session, Query query) {
        SysUser user = (SysUser) session.getAttribute(Constant.GLOBAL_SESSION);
        Pager<NewsArticle> pager = newsService.loadNewsByPage(user.getMerchant_id(), query);
        return pager;
    }

    /**
     * 上传封面图片
     *
     * @param merchantId
     * @param request
     * @return
     */
    @RequestMapping(value = "uploadCover/{merchant_id}", method = RequestMethod.POST)
    @ResponseBody
    public Result gotoDetail(@PathVariable("merchant_id") long merchantId, MultipartHttpServletRequest request) {
        List<BasesiteArticlePic> files = new ArrayList<BasesiteArticlePic>();
        Iterator<String> itr = request.getFileNames();
        String productId = request.getParameter("sid");
        Merchant mer = merchantService.loadMerchantBySid(merchantId);
        while (itr.hasNext()) {
            String _root = Constant.PIC_BASE_PATH;// request.getSession().getServletContext().getRealPath("/");
            /* String _root = request.getServletContext().getRealPath("/"); */
            MultipartFile mpf = request.getFile(itr.next());
            // 文件信息解析
            BasesiteArticlePic productPic = new BasesiteArticlePic();
            productPic.setProductId(Long.valueOf(productId));
            String _orig_name = mpf.getOriginalFilename();
            int _last_dot_pos = _orig_name.lastIndexOf(".");
            productPic.setOriginalName(_orig_name);
            productPic.setFileSize(mpf.getSize() / 1024);
            productPic.setFileType(mpf.getContentType());
            productPic.setFileName(_orig_name);
            if (-1 != _last_dot_pos) {
                productPic.setSuffix(_orig_name.substring(_last_dot_pos));
            }
            try {
                productPic.setBytes(mpf.getBytes());
                fileProcessor(mer.getCompany_name(), _root, merchantId, productPic);
            } catch (IOException e) {
                e.printStackTrace();
            }
            files.add(productPic);
        }
        return new Result(files);
    }

    /**
     * kindEditor图片上传
     *
     * @param merchantId
     * @param request
     * @param response
     */
    @RequestMapping(value = "editorUpload/{merchant_id}", method = RequestMethod.POST)
    public void editorFileUploadPost(@PathVariable("merchant_id") long merchantId,
                                     MultipartHttpServletRequest request, HttpServletResponse response) {
        // 判断提交的请求是否包含文件
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {
            return;
        }

        try {
            response.setContentType("text/html; charset=UTF-8");
            response.setHeader("Cache-Control", "no-cache");
            PrintWriter writer = response.getWriter();
            // 上传文件的返回地址
            Iterator<String> iterator = request.getFileNames();
            while (iterator.hasNext()) {
                MultipartFile mpf = request.getFile(iterator.next());
                String upFileName = mpf.getOriginalFilename();
                String _name = UUID.randomUUID().toString().replaceAll("-", "") + upFileName.substring(upFileName.lastIndexOf("."));
                // 获取磁盘文件绝对路径
                String _biz_path = String.format("%4$s%1$s%4$s%2$s%4$s%5$s%4$s%3$s", BIZ_FILE_PATH_PREFIX, merchantId, _name, "/", DateUtil.getUploadDate());
                // 将文件上传至当前用户业务目录 /WebRoot/static/biz/{merchant_id}/header.png
                String _temp_path = String.format("%1$s%2$s", Constant.PIC_BASE_PATH, _biz_path);
                File _temp_file = new File(_temp_path);
                System.out.println("===================上传文件路径" + _temp_path + "===================上传文件大小" + mpf.getBytes().length);
                FileUtils.writeByteArrayToFile(_temp_file, mpf.getBytes());

                JSONObject object = new JSONObject();
                object.put("state", "SUCCESS");
                object.put("url", "/static" + _biz_path);
                object.put("title", upFileName);
                object.put("original", upFileName);

                writer.write(object.toJSONString());
            }
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件处理
     *
     * @param root
     *            系统根目录
     * @param merchantId
     *            商家ID
     * @param watermarkText
     *            水印文字名称
     * @param productPic
     *            文件数据对象
     * @throws IOException
     */
    private String fileProcessor(String watermarkText, String root, long merchantId, BasesiteArticlePic productPic) {
        // 重新生成文件名
        String _name = UUID.randomUUID().toString().replaceAll("-", "");
        // 获取磁盘文件绝对路径
        String _biz_path = String.format("%5$s%1$s%5$s%2$s%5$s%3$s%4$s", BIZ_FILE_PATH_PREFIX, merchantId, _name,
                productPic.getSuffix(), File.separator);
        productPic.setFileName(_name + productPic.getSuffix());
        productPic.setUrl(_biz_path);
        // 将文件上传至当前用户业务目录 /WebRoot/static/biz/{merchant_id}/header.png
        String _temp_path = String.format("%1$s%2$s", root, productPic.getUrl());
        //File _temp_file = File.createTempFile(_name, productPic.getSuffix());
        File _temp_file = new File(_temp_path);
        System.out.println("===================上传文件路径" + _temp_path);
        try {
            System.out.println("===================上传文件大小" + productPic.getBytes().length);
            FileUtils.writeByteArrayToFile(_temp_file, productPic.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 图片压缩
        //Thumbnails.of(_temp_file).size(300, 600).toFile(new File(_temp_path));
        //_temp_file.delete();
        return _name;

    }

    /**
     * 上传文章图片文件
     *
     * @param merchantId
     *            商家编号
     * @param request
     *            MultipartHttpServletRequest
     * @return Result
     */
    @RequestMapping(value = "uploadNicedit/{merchant_id}", method = RequestMethod.POST)
    @ResponseBody
    public Result uploadNicedit(@PathVariable("merchant_id") long merchantId, MultipartHttpServletRequest request, HttpServletResponse response) {
        List<BasesiteArticlePic> files = new ArrayList<BasesiteArticlePic>();
        Iterator<String> itr = request.getFileNames();
        Merchant mer = merchantService.loadMerchantBySid(merchantId);
        while (itr.hasNext()) {
            String _root = Constant.PIC_BASE_PATH;// request.getSession().getServletContext().getRealPath("/");
            MultipartFile mpf = request.getFile(itr.next());
            // 文件信息解析
            BasesiteArticlePic productPic = new BasesiteArticlePic();
            String _orig_name = mpf.getOriginalFilename();
            int _last_dot_pos = _orig_name.lastIndexOf(".");
            productPic.setOriginalName(_orig_name);
            productPic.setFileSize(mpf.getSize() / 1024);
            productPic.setFileType(mpf.getContentType());
            productPic.setFileName(_orig_name);
            if (-1 != _last_dot_pos) {
                productPic.setSuffix(_orig_name.substring(_last_dot_pos));
            }

            PrintWriter out = null;
            try {
                productPic.setBytes(mpf.getBytes());
                String newFileName = fileProcessor(mer.getCompany_name(), _root, merchantId, productPic);
                out = response.getWriter();
                StringBuilder baseP = new StringBuilder()
                        .append(request.getScheme()).append("://")
                        .append(request.getServerName()).append(":")
                        .append(request.getServerPort()).append("/")
                        .append(merchantId).append("/")
                        .append(Constant.PIC_ART_PATH).append("/");
                JSONObject json_object = new JSONObject();
                json_object.put("done", 0);
                json_object.put("url", baseP.toString() + newFileName);
                json_object.put("width", 120);
                out.print(json_object.toString());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                    out = null;
                }
            }
            files.add(productPic);
        }
        return new Result(files);
    }

    /**
     * 进入编辑或者增加的页面
     *
     * @param session
     * @param sid
     * @param model
     * @return
     */
    @RequestMapping(value = "gotoAdd", method = GET)
    public String gotoArticleEdit(HttpSession session, @RequestParam(value = "sid", required = false) long sid, Model model) {
        if (sid > 0) {// 编辑
            NewsArticle art = newsService.loadNewsById(sid);
            art.setContent(HtmlUtils.htmlEscape(art.getContent()));
            model.addAttribute("pic", art.getOriginalName());
            model.addAttribute("news", art);
            model.addAttribute("isAddNew", 0);
        } else {
            model.addAttribute("news", new NewsArticle());
            model.addAttribute("isAddNew", 1);
        }
        List<NewsArticle> newArticles = new ArrayList<NewsArticle>();
        newArticles = newsService.findTopNews();
        Map<Integer, String> types = new HashMap<Integer, String>();
        types.put(0, "头条新闻");
        types.put(1, "封面新闻");
        model.addAttribute("types", types);
        model.addAttribute("newArticlesList", newArticles);
        return "admin/police/news-add";
    }

    /**
     * 表单提交
     *
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "addOrEditNews", method = POST)
    public Result submitProductForm(NewsArticle news, HttpSession session, HttpServletRequest request) {
        int isaddnew = Integer.parseInt(request.getParameter("isAddNew"));
        long topsid = 0l;

        String topnewsinfo = request.getParameter("topnewsinfo");
        if (!StringUtils.isEmpty(topnewsinfo)) {
            topsid = Long.parseLong(topnewsinfo);
        }

        SysUser user = (SysUser) session.getAttribute(Constant.GLOBAL_SESSION);
        news.setMer_id(user.getMerchant_id());
        news.setStatus(1);
        news.setCreatTime(new Date());
        if (isaddnew == 1) {
            if (news.getType() == 0) {
                news.setPid(0);
            } else {
                news.setPid(topsid);
            }
            return newsService.saveArticle(news);
        }
        return newsService.saveOrUpdate(news);
    }

    /**
     * 删除新闻
     *
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "delNews", method = DELETE)
    public Result deleteArticleById(HttpSession session, @RequestParam("sids") String sids) {
        String[] ids = sids.split(",");
        for (String sid : ids) {
            newsService.deleteNewsById(Long.parseLong(sid));
        }
        return new Result();
    }

    @ResponseBody
    @RequestMapping(value = "editType/{sid}", method = POST)
    public Result editType(@PathVariable("sid") long pid, FormItem fromItem) {
        return newsService.updateType(pid, fromItem.getProp(), fromItem.getVal());
    }

    @RequestMapping(value = "setTime", method = GET)
    public String setTime(@RequestParam("sids") String sid, Model model) {
        List<NewsArticle> articles = new ArrayList<NewsArticle>();
        String[] sids = sid.split(",");
        for (int i = 0; i < sids.length; i++) {
            articles.addAll(newsService.loadNewsTime(Long.parseLong(sids[i])));
//			articles.add(newsService.loadNewsTime(Long.parseLong(sids[i])));
        }
        model.addAttribute("articles", articles);
        model.addAttribute("sids", sid);
        return "admin/police/setTime";
    }

    /**
     * 设置发布时间
     *
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "saveTime", method = POST)
    public Result saveTime(NewsArticle news, HttpSession session) {
        SysUser user = (SysUser) session.getAttribute(Constant.GLOBAL_SESSION);
        news.setMer_id(user.getMerchant_id());
        news.setStatus(1);
        news.setCreatTime(new Date());
        return newsService.saveOrUpdate(news);
    }

    /**
     * 设置发布时间
     *
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "sendNow", method = GET)
    public Result sendNow(@RequestParam("sids") String sids, @RequestParam("time") String date) {
        Result result = new Result();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            result = newsService.sendTime(sids, sdf.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 进图新闻发布的的第二种方式
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "goToadd2", method = GET)
    public String gotoAdd2(Model model) {
        return "admin/police/news-add2";
    }


    /**
     * 进图新闻发布的的第三种方式 从推送新闻中获取
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "goToadd3", method = GET)
    public String gotoAdd3(Model model) {
        List<NewsArticle> newArticles = new ArrayList<NewsArticle>();
        newArticles = newsService.findTopNews();
        Map<Integer, String> types = new HashMap<Integer, String>();
        types.put(0, "头条新闻");
        types.put(1, "封面新闻");
        model.addAttribute("types", types);
        model.addAttribute("newArticlesList", newArticles);
        return "admin/police/news-add3";
    }

    /**
     * 获取推送过来的新闻列表
     * @param query
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "pushnewslist", method = GET)
    public Pager<News> gotoPushNewsList(Query query) {
        Pager<News> pager = newsService.loadPushNewsByPage(query);
        return pager;
    }

    /**
     * 保存推送新闻
     * @param session
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "savenewslist", method = POST)
    public Result saveNewsList(HttpSession session, HttpServletRequest request) {
        long topsid = 0l;
        String id = request.getParameter("id");
        if (StringUtils.isEmpty(id))
            return new Result(Result.FAILURE, "请选择推送的新闻");

        String topnewsinfo = request.getParameter("topnewsinfo");
        if (!StringUtils.isEmpty(topnewsinfo)) {
            topsid = Long.parseLong(topnewsinfo);
        }

        SysUser user = (SysUser) session.getAttribute(Constant.GLOBAL_SESSION);
        NewsArticle news = new NewsArticle();
        news.setMer_id(user.getMerchant_id());
        news.setStatus(1);
        news.setCreatTime(new Date());
        news.setPid(topsid);
        news.setType(topsid == 0 ? 0 : 1);

        return newsService.savePushNewsByPage(Integer.parseInt(id), news);
    }

    /**
     * 发布新闻
     *
     * @param model
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "add2News", method = POST)
    public Result Add2News(HttpServletRequest request, Model model) throws Exception {
        //头条
        Result re = new Result();
        long pid = 0;
        String topUrl = request.getParameter("topUrl");
        if (topUrl.trim() != null) {
            String topPicUrl = request.getParameter("topP");
            String topPic = request.getParameter("topPicName");
            NewsArticle article = new NewsArticle();
            article.setPicCover(topPicUrl);
            article.setOriginalName(topPic);
            article.setType(0);
            article.setPid(0);
            re = newsService.addNewsByUrl(topUrl, article);
            pid = (Integer) re.getData();
        }
        String index = request.getParameter("coverindex");
        String[] deltindex = request.getParameter("deltindex").split(",");
        List<String> tempList = Arrays.asList(deltindex);
        for (int i = 1; i <= Integer.parseInt(index); i++) {
            if (!tempList.contains(i + "")) {
                String iString = String.valueOf(i);
                String cover1 = request.getParameter("cover" + iString);
                if (!cover1.trim().equals("")) {
                    String coverP = request.getParameter("cover" + iString + "P");
                    String coverPname = request.getParameter("cover" + iString + "PicName");
                    NewsArticle article = new NewsArticle();
                    article.setPicCover(coverP);
                    article.setOriginalName(coverPname);
                    article.setType(1);
                    article.setPid(pid);
                    re = newsService.addNewsByUrl(cover1, article);
                }
            }
        }
        return re;
    }


    /**
     * 第三种发布
     *
     * @param model
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "add3News", method = POST)
    public Result Add3News(HttpServletRequest request, Model model) throws Exception {
        //头条
        Result re = new Result();
        String topUrl = request.getParameter("topUrl");
        if (topUrl.trim() != null) {
            String topPicUrl = request.getParameter("topP");
            String topPic = request.getParameter("topPicName");
            NewsArticle article = new NewsArticle();
            article.setPicCover(topPicUrl);
            article.setOriginalName(topPic);
            article.setType(0);
            re = newsService.addNewsByUrl(topUrl, article);
        }
        String cover1 = request.getParameter("cover1");
        if (!cover1.trim().equals("")) {
            String coverP = request.getParameter("cover1P");
            String coverPname = request.getParameter("cover1PicName");
            NewsArticle article = new NewsArticle();
            article.setPicCover(coverP);
            article.setOriginalName(coverPname);
            article.setType(1);
            re = newsService.addNewsByUrl(cover1, article);
        }
        String cover2 = request.getParameter("cover2");
        if (!cover2.trim().equals("")) {
            String coverP = request.getParameter("cover2P");
            String coverPname = request.getParameter("cover2PicName");
            NewsArticle article = new NewsArticle();
            article.setPicCover(coverP);
            article.setOriginalName(coverPname);
            article.setType(1);
            re = newsService.addNewsByUrl(cover2, article);
        }
        return re;
    }


    /**
     * 进入关注人发送消息管理界面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "attention", method = GET)
    public String gotoAttention(Model model) {
        return "admin/police/attention";
    }

    /**
     * 列出所有的消息
     * @param session
     * @param date
     * @param query
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "attentionList", method = GET)
    public Pager<SuperMessage> attention(HttpServletRequest request, HttpSession session, @RequestParam(value = "date") Integer date, Query query) throws Exception {
        String start = request.getParameter("start");
        String end = request.getParameter("end");
        if (!StringUtils.isEmpty(start)) {
            start += " 00:00:00";
        }
        if (!StringUtils.isEmpty(end)) {
            end += " 23:59:59";
        }
        return countAdminService.loadNewsByPage("gh_b6af115f3e1a", query, start, end);
    }

    /**
     * 列出所有的消息
     * @param session
     * @param query
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "attentionExp", method = GET)
    public void attentionexp(HttpServletRequest request, HttpServletResponse response, HttpSession session, Query query) throws Exception {
        query.setPage(0);
        String start = request.getParameter("start");
        String end = request.getParameter("end");
        if (!StringUtils.isEmpty(start)) {
            start += " 00:00:00";
        }
        if (!StringUtils.isEmpty(end)) {
            end += " 23:59:59";
        }
        Pager<SuperMessage> pag = countAdminService.loadNewsByPage("gh_b6af115f3e1a", query, start, end);
        List<SuperMessage> list = pag.getRows();
        Map<String, Object> nqxMap = new LinkedHashMap<String, Object>();
        nqxMap.put("nqxlist", list);
        countAdminService.export(request, response, "xls", "daocMode.xml", nqxMap);
    }

    @ResponseBody
    @RequestMapping(value = "ueditorConfig", method = GET)
    public Pager<SuperMessage> ueditorConfig(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "text/html");

        String rootPath = request.getRealPath("/");

        //out.write( new ActionEnter( request, rootPath).exec() );
        return null;
    }
}
